package com.junzhiit.nengji.cms.web.util.aliyun;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

@Component
public class AliyunOSSClientUtil {
	//log日志
	private static Logger logger = Logger.getLogger(AliyunOSSClientUtil.class);
	//阿里云API的内或外网域名
	private static String ENDPOINT;
	//阿里云API的密钥Access Key ID
	private static String ACCESS_KEY_ID;
	//阿里云API的密钥Access Key Secret
	private static String ACCESS_KEY_SECRET;
	
	private static String BUCKET_NAME;
	
	@Value("${oss.endpoint.name}")
	public void setEndpoint(String endpoint) {
		AliyunOSSClientUtil.ENDPOINT = endpoint;
	}

	@Value("${oss.backet.name}")
	public void setBucketName(String BucketName) {
		AliyunOSSClientUtil.BUCKET_NAME = BucketName;
	}


	//初始化属性
	static{
		ACCESS_KEY_ID = OSSClientConstants.ACCESS_KEY_ID;
		ACCESS_KEY_SECRET = OSSClientConstants.ACCESS_KEY_SECRET;
	}
	
	/**
	 * 获取阿里云OSS客户端对象
	 * @return ossClient
	 */
	public static  OSSClient getOSSClient(){
		return new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	}
 
	/**
	 * 创建存储空间
	 * @param ossClient      OSS连接
	 * @param bucketName 存储空间
	 * @return
	 */
	public  static String createBucketName(OSSClient ossClient,String bucketName){
		//存储空间
		final String bucketNames=bucketName;
		if(!ossClient.doesBucketExist(bucketName)){
			//创建存储空间
			Bucket bucket=ossClient.createBucket(bucketName);
			logger.info("创建存储空间成功");
			return bucket.getName();
		}
		return bucketNames;
	}
	
	/**
	 * 创建模拟文件夹
	 * @param ossClient oss连接
	 * @param bucketName 存储空间
	 * @param folder   模拟文件夹名如"qj_nanjing/"
	 * @return  文件夹名
	 */
	public  static String createFolder(OSSClient ossClient,String bucketName,String folder){
		//文件夹名 
		final String keySuffixWithSlash =folder;
		//判断文件夹是否存在，不存在则创建
		if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){
			//创建文件夹
			ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
			logger.info("创建文件夹成功");
			//得到文件夹名
			OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
			String fileDir=object.getKey();
			return fileDir;
		}
		return keySuffixWithSlash;
	}
	
	 /**  
	    * 根据key删除OSS服务器上的文件  
	    * @param ossClient  oss连接
	    * @param bucketName  存储空间 
	    * @param folder  模拟文件夹名 如"qj_nanjing/"
	    * @param key Bucket下的文件的路径名+文件名 如："upload/cake.jpg"
	    */    
	   public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key){    
		    ossClient.deleteObject(bucketName, folder + key);   
	        logger.info("删除" + bucketName + "下的文件" + folder + key + "成功");  
	   } 
	
	/**
	 * 上传图片至OSS
	 * @param ossClient  oss连接
	 * @param file 上传文件
	 * @param bucketName  存储空间
	 * @param folder 模拟文件夹名 如"qj_nanjing/"
	 * @return String 返回的唯一MD5数字签名
	 * */
	public static  String uploadObject2OSS(InputStream file,String name, String bucketName, String folder) {
		String resultStr = null;
		try {
			OSSClient ossClient=AliyunOSSClientUtil.getOSSClient();
			//文件名
			/* String prefix=name.substring(name.lastIndexOf("."));
		     String fileName = UUID.randomUUID().toString().replaceAll("-", "") + prefix;*/
			
            //上传文件   (上传文件流的形式)
            createFolder(ossClient, bucketName, folder);
            ossClient.putObject(bucketName, folder + name, file);  
			//解析结果
			resultStr = name;
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);  
		}
		return resultStr;
	}
 
	/**
	 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
	 * @param fileName 文件名
	 * @return 文件的contentType
	 */
	public static  String getContentType(String fileName){
		//文件的后缀名
		String fileExtension = fileName.substring(fileName.lastIndexOf("."));
		if(".bmp".equalsIgnoreCase(fileExtension)) {
			return "image/bmp";
		}
		if(".gif".equalsIgnoreCase(fileExtension)) {
			return "image/gif";
		}
		if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)  || ".png".equalsIgnoreCase(fileExtension) ) {
			return "image/jpeg";
		}
		if(".html".equalsIgnoreCase(fileExtension)) {
			return "text/html";
		}
		if(".txt".equalsIgnoreCase(fileExtension)) {
			return "text/plain";
		}
		if(".vsd".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.visio";
		}
		if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.ms-powerpoint";
		}
		if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
			return "application/msword";
		}
		if(".xml".equalsIgnoreCase(fileExtension)) {
			return "text/xml";
		}
		//默认返回类型
		return "image/jpeg";
	}
	
	/**
	 * 
	 * TODO 移动文件
	 * @author PeterMo
	 * @param backetName OSS名称
	 * @param fileName 文件名称
	 * @param destinationKey 目标路径
	 * @param sourceKey 原路径
	 * @time 2018年8月22日 下午4:02:46
	 * @return boolean
	 *
	 */
	public static  boolean moveFile(String backetName,String fileName,String destinationKey,String sourceKey){
		boolean isSucceed = true;
		try {
			createFolder(AliyunOSSClientUtil.getOSSClient(), backetName, destinationKey);
			// 创建OSSClient实例。
			OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
			// 创建CopyObjectRequest对象。
			CopyObjectRequest copyObjectRequest = new CopyObjectRequest(backetName, sourceKey+fileName, backetName, destinationKey+fileName);
			// 复制文件。
			CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
			System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (Exception e) {
			isSucceed = false;
			logger.error(e.getMessage(), e);
		}
		return isSucceed;
	}
	
	/**
	 * 
	 * TODO 删除图片
	 * @author PeterMo
	 * @param bucket 阿里云API的bucket名称
	 * @param filefullPath 文件路径
	 * @time 2018年8月22日 下午4:36:22
	 * @return boolean
	 *
	 */
	public static boolean removeFile(String bucket,String filefullPath){
		boolean isSucceed = true;
		try {
			// 创建OSSClient实例。
			OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
			ossClient.deleteObject(bucket, filefullPath);
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (Exception e) {
			isSucceed = false;
			logger.error(e.getMessage(), e);
		}
		return isSucceed;
	}
	
	/**
	 * 
	 * TODO 图片下载
	 * @param bucket 阿里云API的bucket名称
	 * @param filefullPath 文件路径
	 * @param localFile 保存文件路径
	 * @author PeterMo
	 * @time 2018年9月19日 上午9:43:06
	 * @return void
	 */
	public static void download(String filefullPath,String localFile,String fileName){
		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
		ossClient.getObject(new GetObjectRequest(BUCKET_NAME, filefullPath), new File(localFile+fileName));
		// 关闭OSSClient。
		ossClient.shutdown();
	}
	
	/**
	 * 
	 * TODO 根据流方式下载
	 * @author PeterMo
	 * @time 2018年9月19日 下午4:02:30
	 * @return void
	 */
	public static void flowDownload(HttpServletResponse response,String filefullPath){
		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
		OSSObject ossObject = ossClient.getObject(BUCKET_NAME, filefullPath);
		// 读取文件内容。
		System.out.println("Object content:");
		BufferedInputStream input = new BufferedInputStream(ossObject.getObjectContent());
		byte[] buffBytes = new byte[1024];
		try {
			OutputStream outputStream = response.getOutputStream();
			int read = 0;
			while ((read = input.read(buffBytes)) != -1) {
			     outputStream.write(buffBytes, 0, read);
			}
			outputStream.flush();
			outputStream.close();
			input.close();
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	 
    
	//测试
	public static void main(String[] args) {
		
		//flowDownload("app/about-lege-1.jpg");
		//上传文件
		/*String files="F:\\img\\goods\\00a36878d8114a48ac31447976e1674b.jpg,F:\\img\\goods\\00b0b4438ac64950bb982b010a9a48ef.jpg";
		String[] file=files.split(",");
		try {
			for(String filename:file){
				File filess=new File(filename);
				InputStream inputStream = new FileInputStream(filess);
				String md5key = AliyunOSSClientUtil.uploadObject2OSS(inputStream, filename, "bainaeco-dev", "test/");  
				//logger.info("上传后的文件MD5数字唯一签名:" + md5key);  
				//上传后的文件MD5数字唯一签名:40F4131427068E08451D37F02021473A
			}
		} catch (Exception e) {
			// TODO: handle exception
		}*/
		try {
			File[] files = new File("C://Users//Administrator//Desktop//11").listFiles();
	        for (int i = 0; i < files.length; i++)
	        {
	            if(files[i].getName().replaceAll("(.jpg|.png|.bmp|.gif)+","").length() != files[i].getName().length())
	            {
	            	InputStream inputStream = new FileInputStream(files[i]);
	            	String md5key = AliyunOSSClientUtil.uploadObject2OSS(inputStream, files[i].getName(), "bainaeco-sit", "advertise/");  
	            	System.out.println(i+"---------"+files[i].getName());
	            }
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}
		//removeFile(BACKET_NAME,"goods/00a36878d8114a48ac31447976e1674b.jpg");
	}

	
}
